//
//  DiscoverSquare.m
//  Feeds2
//
//  Created by cos on 2020/11/25.
//  Copyright © 2020 cos. All rights reserved.
//

#import "DiscoverSquare.h"
#import <Foundation/Foundation.h>
#import "QueryInformationViewController.h"
#import "customCell.h"
#import "Single.h"
#import "footview.h"
#import "AFNetworking.h"
#import "MPlabel.h"
#import "MJRefresh.h"
#define RGBACOLOR(R, G, B, A) [UIColor colorWithRed:((R) / 255.0f) green:((G) / 255.0f) blue:((B) / 255.0f) alpha:A]
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface DiscoverSquare ()<UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>

@property(strong,nonatomic) NSDictionary *date;
@property(strong,nonatomic) NSDictionary *place;
@property(assign,nonatomic) NSDictionary *acquaintance;
// 数据源数组
//@property(strong,nonatomic) NSMutableArray *datalist;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISearchController *searchController;
// 搜索结果数组
@property (nonatomic, strong) NSMutableArray *results;
@property(assign,nonatomic)int number;
@property(assign,nonatomic)int count;
@property(assign,nonatomic)UIButton *button;
@property int pages;

//scrollview
@property UIScrollView * scrollView;
//like
@property Boolean *likestate;
@end

@implementation DiscoverSquare

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:135/255.0 green:206/255.0 blue:250/255.0 alpha:1];
    _pages = 1;
    _count = 0;
    _likestate = false;
    self.navigationItem.title = @"广场";  
    //
    [self storedata];
    
    //111

}
-(void)storedata{
   [[Single sharedInstance].datalist removeAllObjects];
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
     manager.requestSerializer = [AFJSONRequestSerializer serializer];
     manager.responseSerializer = [AFJSONResponseSerializer serializer];
    /* NSDictionary *dict = @{
                            @"name":@"zhangsan@sysu.edu.cn",
                            @"password":@"test"
                            };
     [manager POST:@"http://172.18.178.56/api/user/login/pass" parameters:dict headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
     
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"@login");
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
     }];*/
     //
     //111
     //AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
     manager.requestSerializer = [AFJSONRequestSerializer serializer];
     manager.responseSerializer = [AFJSONResponseSerializer serializer];
     [manager GET:@"http://172.18.178.56/api/content/public?page=1&eachPage=10" parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         //
         NSDictionary *dict = (NSDictionary *)responseObject;
         NSDictionary *dict2 = (NSDictionary *)dict[@"Data"];
         
         for(id key2 in dict2){
             
             id key = key2[@"Data"];
             //album
             NSMutableArray * dic_image = [[NSMutableArray alloc]init];
             NSDictionary * album =(NSDictionary *)key[@"Album"][@"Images"];
             
             for(id key3 in album){
                 NSString * temp_iamge_url = [[NSString alloc] initWithFormat:@"%@%@",@"http://172.18.178.56/api/thumb/",key3[@"Thumb"]];
                 [dic_image addObject:temp_iamge_url];
                 //NSLog(@"%@",temp_iamge_url);
             }
             //album
             //NSLog(@"%@",key);
             id namek = key2[@"User"];
             NSDictionary *temp = [[NSDictionary alloc]init];
             //
             NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
             [formatter setDateStyle:NSDateFormatterMediumStyle];
             [formatter setTimeStyle:NSDateFormatterShortStyle];
             [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
             // 时间戳转时间的方法
             NSString *s = key[@"EditDate"];
             NSLog(@"%@",s);
             long long  myInt = [s longLongValue];
             NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:(myInt/1000/*+57600*/)];
             NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
             //
             NSString *cnum = [NSString stringWithFormat:@"%@",key[@"CommentNum"]];
             NSString *lnum = [NSString stringWithFormat:@"%@",key[@"LikeNum"]];
             temp = @{@"Date":confromTimespStr,
                      @"Name":key[@"Name"],
                      @"Detail":key[@"Detail"],
                      @"CommentNum":cnum,
                      @"LikeNum":lnum,
                      @"Id":key[@"ID"],
                      @"OwnId":key[@"OwnID"],
                      @"UserName":namek[@"Name"],
                      @"image":dic_image
             };
             [[Single sharedInstance].datalist addObject:temp];
             [_tableView reloadData];
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         //
     }];
     
}

-(void)refreshData{
    
  [self storedata];
    [_tableView reloadData];
  [_tableView.mj_header endRefreshing];
 
}

-(void)viewWillAppear:(BOOL)animated{
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"data" ascending:NO];
    [[Single sharedInstance].datalist sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [self setBack];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-20, self.view.frame.size.height) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    
    // 创建UISearchController, 这里使用当前控制器来展示结果
    UISearchController *search = [[UISearchController alloc]initWithSearchResultsController:nil];
    // 设置结果更新代理
    search.searchResultsUpdater = self;
    // 因为在当前控制器展示结果, 所以不需要这个透明视图
    search.obscuresBackgroundDuringPresentation = NO;
    self.searchController = search;
    // 将searchBar赋值给tableView的tableHeaderView
    self.tableView.tableHeaderView = search.searchBar;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    //上拉加载
    [self setupUpRefresh];
}

-(void)setBack{
    CAGradientLayer *l = [[CAGradientLayer alloc] init];
    l.colors = @[(__bridge id)UIColorFromRGB(0x87cefa).CGColor , (__bridge id)UIColorFromRGB(0xffc0cb).CGColor];
    l.startPoint = CGPointMake(0, 0);
    l.endPoint = CGPointMake(1, 1);
    l.frame = self.view.bounds;
    [self.view.layer addSublayer:l];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchController.active ) {
        return _results.count;
        
    } else {
        return [Single sharedInstance].datalist.count;
    }
}
/*- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}*/

-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView* v = [[UIView alloc]init];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView* v = [[UIView alloc]init];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     return 90;
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    
    return _tableView;
}

- (NSMutableArray *)results {
    if (_results == nil) {
        _results = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _results;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"cell";
    customCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        cell = [[customCell alloc]initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:identifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (self.searchController.active ) {
        [cell setLabel1Text:self.results[indexPath.section][@"Name"] label2Text:self.results[indexPath.section][@"CommentNum"] label3Text:self.results[indexPath.section][@"LikeNum"]];
    } else {
        [cell setLabel1Text:[Single sharedInstance].datalist[indexPath.section][@"Name"] label2Text:[Single sharedInstance].datalist[indexPath.section][@"CommentNum"] label3Text:[Single sharedInstance].datalist[indexPath.section][@"LikeNum"]];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [Single sharedInstance].commentid = [Single sharedInstance].datalist[indexPath.section][@"Id"];
    [Single sharedInstance].fatherid = [Single sharedInstance].datalist[indexPath.section][@"OwnId"];
    CGRect screenFrame = [UIScreen mainScreen].bounds;
    int screenWidth = screenFrame.size.width;
    int screenHeight = screenFrame.size.height;
    QueryInformationViewController *newpage = [[QueryInformationViewController alloc] init];
    
    newpage.label1 = [[UILabel alloc]initWithFrame:CGRectMake(20, screenHeight/10-30, 250, 60)];
    newpage.label1.text = [Single sharedInstance].datalist[indexPath.section][@"Date"];
    newpage.label2 = [[UILabel alloc]initWithFrame:CGRectMake(20, screenHeight/10+30, 250, 60)];
    newpage.label2.text = [Single sharedInstance].datalist[indexPath.section][@"Name"];
    newpage.labelname = [[UILabel alloc]initWithFrame:CGRectMake(20, screenHeight/10, 250, 60)];
    newpage.labelname.text = [Single sharedInstance].datalist[indexPath.section][@"UserName"];
    newpage.label3 = [[MPlabel alloc] init];
    [newpage.label3 setLabelWithOrigin:CGPointMake(20, screenHeight/10+80) mutableText:[Single sharedInstance].datalist[indexPath.section][@"Detail"] mutableFont:[UIFont boldSystemFontOfSize:20] margin:0];
    
    newpage.viewww = [[UIView alloc]init];
    //imagelist
    newpage.imagelist = [Single sharedInstance].datalist[indexPath.section][@"image"];
    //NSLog(@"%@",newpage.imagelist);
    //imagelist
    [self.navigationController pushViewController:newpage animated:YES];
    //[self customPresentWith:@"cube"controller:newpage];//pageCurl cube oglFlip
}

-(void)BtnClick:(UIButton *)btn{
    if(_likestate){
        [btn setImage:[UIImage imageNamed:@"like1.png"] forState:UIControlStateNormal];
        _likestate = !_likestate;
    }
    else{
        [btn setImage:[UIImage imageNamed:@"like2.png"] forState:UIControlStateNormal];
        _likestate = !_likestate;
    }
    
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *inputStr = searchController.searchBar.text ;
    
    if (self.results.count > 0) {
        [self.results removeAllObjects];
    }
    for (NSDictionary *dictionary in [Single sharedInstance].datalist) {
        //NSString* str = [dictionary[@"date"] componentsJoinedByString:@""];
        NSString* str = dictionary[@"Name"];
        /*NSString* str2 = dictionary[@"Name"];
        NSString* str3 = dictionary[@"Detail"];
        str = [str stringByAppendingString:str2];
        str = [str stringByAppendingString:str3];*/
        if ([str.lowercaseString rangeOfString:inputStr.lowercaseString].location != NSNotFound) {
            [self.results addObject:dictionary];
        }
    }
    
    [self.tableView reloadData];
}

//加载数据
- (void)setupUpRefresh
{
    footview *refreshFooterView = [footview refreshFooterView];
    refreshFooterView.hidden = YES;
    self.tableView.tableFooterView = refreshFooterView;
}

/**
 *  加载更多数据
 */
- (void)loadMoreDatas
{
    //
    ++_pages;
    
    NSString *url3 =[[NSString alloc]initWithFormat:@"%@%d%@",@"http://172.18.178.56/api/content/public?page=",_pages,@"&eachPage=10"];
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        [manager GET:url3 parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //
            NSDictionary *dict = (NSDictionary *)responseObject;
            NSDictionary *dict2 = (NSDictionary *)dict[@"Data"];
            
            for(id key2 in dict2){
                
                id key = key2[@"Data"];
                //album
                NSMutableArray * dic_image = [[NSMutableArray alloc]init];
                NSDictionary * album =(NSDictionary *)key[@"Album"][@"Images"];
                
                for(id key3 in album){
                    NSString * temp_iamge_url = [[NSString alloc] initWithFormat:@"%@%@",@"http://172.18.178.56/api/thumb/",key3[@"Thumb"]];
                    [dic_image addObject:temp_iamge_url];
                    //NSLog(@"%@",temp_iamge_url);
                }
                //album
                //NSLog(@"%@",key);
                id namek = key2[@"User"];
                NSDictionary *temp = [[NSDictionary alloc]init];
                //
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateStyle:NSDateFormatterMediumStyle];
                [formatter setTimeStyle:NSDateFormatterShortStyle];
                [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
                // 时间戳转时间的方法
                NSString *s = key[@"EditDate"];
                NSLog(@"%@",s);
                long long  myInt = [s longLongValue];
                NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:(myInt/1000/*+57600*/)];
                NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
                //
                NSString *cnum = [NSString stringWithFormat:@"%@",key[@"CommentNum"]];
                NSString *lnum = [NSString stringWithFormat:@"%@",key[@"LikeNum"]];
                temp = @{@"Date":confromTimespStr,
                         @"Name":key[@"Name"],
                         @"Detail":key[@"Detail"],
                         @"CommentNum":cnum,
                         @"LikeNum":lnum,
                         @"Id":key[@"ID"],
                         @"OwnId":key[@"OwnID"],
                         @"UserName":namek[@"Name"],
                         @"image":dic_image
                };
                [[Single sharedInstance].datalist addObject:temp];
                [_tableView reloadData];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //
        }];
    //
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // 结束刷新状态, 隐藏FooterView
        self.tableView.tableFooterView.hidden = YES;
    });
}

#pragma mark UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSMutableArray * list =[Single sharedInstance].datalist;
    // 获取当前contentView滑动的位置(对应contentSize)
    CGFloat contenOffsetY = scrollView.contentOffset.y;
    
    // 如果tableView还没有数据或footerView在显示时, 直接返回
    if (list.count == 0 || self.tableView.tableFooterView.hidden == NO)
    {
        return;
    }
    
    // 最后一个Cell显示时contentOffSetY应该在的最小位置(内容高度 + 边框 - 显示窗口高度 - footrerView高度)
    CGFloat targetContentOffsetY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.frame.size.height - self.tableView.tableFooterView.frame.size.height;
    
    // 若滑动位置在目标位置下(显示到最后一个Cell)时
    if (contenOffsetY >= targetContentOffsetY)
    {
        // 显示footerView
        self.tableView.tableFooterView.hidden = NO;
        
        // 加载更多数据
        [self loadMoreDatas];
    }
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cornerRadius = 10;
    cell.backgroundColor = UIColor.clearColor;
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef pathRef = CGPathCreateMutable();
    CGRect bounds = CGRectInset(cell.bounds, 0, 0);
    {
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMinX(bounds), CGRectGetMidY(bounds), cornerRadius);
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
        CGPathCloseSubpath(pathRef);
        layer.path = pathRef;
        backgroundLayer.path = pathRef;
        CFRelease(pathRef);
        layer.fillColor = [UIColor whiteColor].CGColor;
        layer.strokeColor = [UIColor lightGrayColor].CGColor;

        UIView *roundView = [[UIView alloc] initWithFrame:bounds];
        
        [roundView.layer insertSublayer:layer atIndex:0];
        roundView.backgroundColor = UIColor.clearColor;
        
        cell.backgroundView = roundView;
        
        UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:bounds];
        backgroundLayer.fillColor = [UIColor cyanColor].CGColor;
        [selectedBackgroundView.layer insertSublayer:backgroundLayer atIndex:0];
        selectedBackgroundView.backgroundColor = UIColor.clearColor;
        cell.selectedBackgroundView = selectedBackgroundView;

    }
}

- (void)customPresentWith:(NSString *)type
               controller:(QueryInformationViewController *)view{
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:view];
    CATransition *animation = [CATransition animation];
    animation.duration = 1.0;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = type;
    //可以改变subtype的类型
    animation.subtype = kCATransitionFromLeft;
    [self.view.window.layer addAnimation:animation forKey:nil];
    [self presentViewController:nav animated:YES completion:nil];
}

@end

